<?php
namespace app\index\business;
use app\index\business\BaseBusiness;
use app\index\controller\BaseController;
use app\index\model\Project;
use app\index\model\Position;
use app\index\model\UserCollectType;
use app\libs\Predis;
use app\libs\SendSms;
use think\Config;
use think\Db;
use think\Request;

class Crm extends BaseBusiness
{
    /**
     * 项目列表
     * @param $reqData
     * @param $dispatch
     * @param int $page
     * @param int $limit
     * @return array
     * @throws
     */
    public function listProject($reqData,$dispatch,$page = 0,$limit = 10){
        if (!$dispatch['user_no']){
            return $this->error('用户身份校验失败');
        }
       
        $obj = Db::table('cq_project')
            ->alias('p')
            ->join('cq_user u','p.user_no = u.user_no','LEFT')
            ->join('cq_project_dynamic c','p.recent_id=c.id','LEFT')
            ->field('p.* ,u.username,c.title as recent,c.url')
            ->where('p.user_no',$dispatch['user_no'])
            ->where('p.status',1);
        if ($reqData['is_monitor']==1){
            $obj->where('p.is_monitor',1);
        }
        if ($reqData['follow_status']){
            $obj->where('p.follow_status',$reqData['follow_status']);
        }
        if ($reqData['customer']){
            $obj->where('p.customer',$reqData['customer']);
        }
        if ($reqData['project_name']){
            $obj->where('p.project_name','like','%'.$reqData['project_name'].'%');
        }
        if ($reqData['company_name']){
        	$obj->where('p.company_name','like','%'.$reqData['company_name'].'%');
        }
        if ($reqData['beginTime']){
            $obj->where('p.created_at','egt',strtotime($reqData['beginTime']));
        }
        if ($reqData['endTime']){
        	$obj->where('p.created_at','lt',strtotime($reqData['endTime']));
        }
       
        // 设置分页数据
        Config::set('paginate.page',bcadd($page,1));
        $origin = $obj->order('p.updated_at','desc')->paginate($limit)->toArray();
        $data = $origin['data'];
        $total = $origin['total'];
        
        foreach ($data as &$v){
            $v['created_at']=date('Y-m-d H:i:s',$v['created_at']);
            $v['follow_name']=project_status($v['follow_status']);
            
            
            $v['num']=db('project a')
            ->join('project_visite b','a.id=b.project_id','inner')
            ->where("a.company_name like '%{$v['company_name']}%'")
            ->count('b.id');
            
            
            //项目最新动态
            $recent=[];
          
            $v['recent']=$recent;
            
            
            
        }
       
        $result = compact('data','total');
        return $this->success('success',1,$result);
    }

    /**
     * add 项目
     * @param $reqData
     * @param $dispatch
     * @return array
     */
    public function addProject($reqData,$dispatch){
        if (!$dispatch['user_no']){
            return $this->error('用户身份校验失败');
        }
        $reqData['user_no'] = $dispatch['user_no'];
        $reqData['created_at'] = $reqData['updated_at'] = time();
        $reqData['status'] = 1;
        $reqData['is_monitor']=2;
        if($reqData['is_monitor'] ==1) $reqData['monited_at'] = time();
        // 判断用户是否已经添加过这个项目 如果是手动添加项目直接跳过此验证
        if ($reqData['s_type'] != 8){
            $id =  Db::table('cq_project')->where('user_no',$dispatch['user_no'])
                ->where('s_type',$reqData['s_type'])
                ->where('identification',$reqData['identification'])
                ->where('status',1)
                ->column('id');
            if ($id){
                return $this->error('你已经添加过这个项目了');
            }
        }
        // 整理数据
        Db::startTrans();
        try {
        	$department_id=db('user a')
        	->join('position b','a.rolo_id=b.id','INNER')
        	->join('department c','b.belong=c.id','INNER')
        	->where(['a.user_no'=> $reqData['user_no']])
        	->value('b.id');
        	
        	$reqData['department_id']=$department_id;
            // 添加一条项目记录
            $p_id = Db::table('cq_project')->insertGetId($reqData);
            // 记录日志 整理数据
            $log['project_id'] = $p_id;
            $log['user_no'] = $dispatch['user_no'];
            $log['project_name'] = $reqData['project_name'];
            $log['contact'] = $reqData['contact'];
            $log['phone'] = $reqData['phone'];
            $log['email'] = $reqData['email'];
            $log['follow_status'] = $reqData['follow_status'];
            $log['customer'] = $reqData['customer'];
            $log['is_monitor'] = $reqData['is_monitor'];
            $log['remark'] = $reqData['remark'];
            
            $log['visite_time'] = $reqData['visite_time'];
            $log['visite_address'] = $reqData['visite_address'];
            $log['visite_man'] = $reqData['visite_man'];
            $log['effect'] = $reqData['effect'];
            $log['leader_name'] = $reqData['leader_name'];
            $log['leader_tel'] = $reqData['leader_tel'];
            $log['leader_img'] = $reqData['leader_img'];
            
            $log['monited_at'] = 0;
            $log['status'] = 1;
            $log['department_id'] =$department_id;
            $log['created_at'] = $log['updated_at'] = time();
            
            if ($log['is_monitor'] ==1) $log['monited_at'] = time();
            Db::table('cq_project_history')->insert($log);

            if ($reqData['s_type'] != 8){
                $tbl = UserCollectType::$tableName .= Config::get('collect.'.$reqData['s_type']);
                $model = new UserCollectType();
                $model->table($tbl)
                    ->where(['user_no'=>$reqData['user_no'],'status'=>1,'identification'=>$reqData['identification']])
                    ->update(['is_project'=>1,'updated_at'=>time()]);
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            var_dump($e->getMessage());
            Db::rollback();
            return $this->error('添加失败');
        }
        $this->result['status'] = 1;
        $this->result['msg'] = '添加成功';
        return $this->result;
    }

    /**
     * edit 项目
     * @param $reqData
     * @param $dispatch
     * @return array
     */
    public function editProject($reqData,$dispatch){
        if (!$dispatch['user_no']){
            return $this->error('用户身份校验失败');
        }
        // 判断用户是否已经添加过这个项目
        $id =  Db::table('cq_project')->where('user_no',$dispatch['user_no'])
            ->where('id',$reqData['project_id'])
            ->where('status',1)
            ->column('id');

        if (!$id){
            return $this->error('你从没有添加过这个项目了');
        }
        
        $department_id=db('user a')
        ->join('position b','a.rolo_id=b.id','INNER')
        ->join('department c','b.belong=c.id','INNER')
        ->where(['a.user_no'=> $dispatch['user_no']])
        ->value('b.id');
        
        // 整理数据
        $project_arr['project_name'] = $reqData['project_name'];
        $project_arr['contact'] = $reqData['contact'];
        $project_arr['career'] = $reqData['career'];
        $project_arr['company_name'] = $reqData['company_name'];
        $project_arr['phone'] = $reqData['phone'];
        $project_arr['email'] = $reqData['email'];
        $project_arr['follow_status'] = $reqData['follow_status'];
        $project_arr['customer'] = $reqData['customer'];
        $project_arr['is_monitor'] = $reqData['is_monitor'];
        $project_arr['remark'] = $reqData['remark'];      
        $project_arr['leader_name'] = $reqData['leader_name'];
        $project_arr['leader_tel'] = $reqData['leader_tel'];
        $project_arr['leader_img'] = $reqData['leader_img'];
        
        $project_arr['updated_at'] = time();

        $insert_log['project_id'] = $reqData['project_id'];
        $insert_log['user_no'] = $dispatch['user_no'];
        $insert_log['project_name'] = $reqData['project_name'];
        $insert_log['contact'] = $reqData['contact'];
        $insert_log['phone'] = $reqData['phone'];
        $insert_log['email'] = $reqData['email'];
        $insert_log['follow_status'] = $reqData['follow_status'];
        $insert_log['customer'] = $reqData['customer'];
        $insert_log['is_monitor'] = $reqData['is_monitor'];
        $insert_log['remark'] = $reqData['remark'];
        
        $insert_log['visite_time'] = $reqData['visite_time'];
        $insert_log['visite_address'] = $reqData['visite_address'];
        $insert_log['visite_man'] = $reqData['visite_man'];
        $insert_log['effect'] = $reqData['effect'];
        $insert_log['leader_name'] = $reqData['leader_name'];
        $insert_log['leader_tel'] = $reqData['leader_tel'];
        $insert_log['leader_img'] = $reqData['leader_img'];
        
        $insert_log['status'] = 1;
        $insert_log['department_id'] = $department_id;
        $insert_log['created_at'] = $insert_log['updated_at'] = time();

        Db::startTrans();
        try {
            // edit一条项目记录
            Db::table('cq_project')->where('id',$reqData['project_id'])->update($project_arr);
            // 记录日志
            Db::table('cq_project_history')->insert($insert_log);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            var_dump($e->getMessage());
            Db::rollback();
            return $this->error('编辑失败');
        }
        $this->result['status'] = 1;
        $this->result['msg'] = '编辑成功';
        return $this->result;
    }

    /**
     * 项目详情
     * @param $id
     * @param $dispatch
     * @return array
     * @throws
     */
    public function detailProject($id,$dispatch){
    	if (!$dispatch['user_no']){
    		return $this->error('用户身份校验失败');
    	}
    	// 判断用户是否已经添加过这个项目
    	$project =  Db::table('cq_project')->where('user_no',$dispatch['user_no'])
    	->where('id',$id)
    	->where('status',1)
    	->find();
    	if (!$project){
    		return $this->error('发生未知错误');
    	}
    	if(!empty($project['city_ids'])){
    		$city_id_str=$project['city_ids'];
    		$city_name=Db::connect(config('db_yd'))->table('yd_city')
    		->where("id in ($city_id_str)")
    		->column('city_name');
    		$project['city_names']=implode(',',$city_name);
    	}else{
    		$project['city_names']="";
    	}
    	//项目最新动态
    	$recent=[];
    	/* if ($project['is_monitor']==1){
    		$company_name=db('project_monit')->where(['project_id'=>$project['id']])->value('company_name');
    		$com_id=Db::connect(config('db_yd'))->table('yd_companys')->where(['status'=>1,'company_name'=>$company_name])->value('id');
    		if (!empty($com_id)){
    			
    			$recent=Db::connect(config('db_yd'))
    			->table('yd_companys_news a')
    			->field('b.news_name as title,b.url,b.create_time as updated_at,b.froms')
    			->join('yd_news b','a.news_id=b.id','left')
    			->where(['a.com_id'=>$com_id,'b.status'=>1])
    			->order('b.create_time desc')->paginate(15);
    			
    		}
    	} */
    	
    	$this->result['status'] = 1;
    	$this->result['msg'] = 'success';
    	$this->result['data'] = $project;
    	$this->result['recent'] = $recent;
    	return $this->result;
    }

    /**
     * 项目日志
     * @param $id
     * @param $dispatch
     * @return array
     * @throws
     */
    public function logProject($id,$dispatch,$page,$limit)
    {
        if (!$dispatch['user_no']){
            return $this->error('用户身份校验失败');
        }
        // 判断用户是否已经添加过这个项目
        $project =  Db::table('cq_project')->where('user_no',$dispatch['user_no'])
            ->where('id',$id)
            ->where('status',1)
            ->column('id');
        if (!$project){
            return $this->error('发生未知错误');
        }

        // 查询该项目的历史log
        Config::set('paginate.page',bcadd($page,1));
        $history = DB::table('cq_project_history')
            ->where('user_no',$dispatch['user_no'])
            ->where('project_id',$id)
            ->order('updated_at','desc')
            ->paginate($limit)
            ->toArray();
        foreach ($history['data'] as &$v){
            $v['created_at']=date('Y-m-d H:i:s',$v['created_at']);
            $v['follow_status']=project_status($v['follow_status']);
            $v['monited_at']=date('Y-m-d H:i:s',$v['monited_at']);
        }

        $this->result['status'] = 1;
        $this->result['msg'] = 'success';
        $this->result['data'] = $history;
        return $this->result;
    }

    /**
     * 项目的监控和取消
     * @param $id
     * @param $monitor_status
     * @param $dispatch
     * @return array
     * @throws \think\Exception
     */
    public function monitorProject($id,$monitor_status,$dispatch)
    {
        if (!$dispatch['user_no']){
            return $this->error('用户身份校验失败');
        }
        if ($monitor_status != 1 && $monitor_status != 2) {
           return $this->error('参数不合法');
        }
        if (!preg_match("/^[1-9][0-9]*$/", $id)) {
            return $this->error('参数不合法');
        }
        // 判断用户是否已经添加过这个项目
        $res =  Db::table('cq_project')->where('user_no',$dispatch['user_no'])
            ->where('id',$id)
            ->where('status',1)
            ->field('is_monitor')
            ->find();
        if (!$res){
            return $this->error('发生未知错误');
        }
        if ($res['is_monitor'] == $monitor_status){
            return $this->error('状态错误了');
        }
        if ($monitor_status == 1){
            $upd = ['is_monitor' => $monitor_status, 'monited_at' => time(), 'updated_at' => time()];
        }
        if ($monitor_status == 2){
            $upd = ['is_monitor' => $monitor_status, 'updated_at' => time()];
        }
        $row = Db::table('cq_project')->where('id',$id)->update($upd);
        if ($row !=1){
            return $this->error('修改失败');
        }
        return $this->success('success',1,[]);
    }

    /**
     * 删除项目
     * @param $id
     * @param $dispatch
     * @return array
     * @throws \think\Exception
     */
    public function delProject($id,$dispatch)
    {
        if (!$dispatch['user_no']){
            return $this->error('用户身份校验失败');
        }
        // 判断用户是否已经添加过这个项目
        $res =  Db::table('cq_project')->where('user_no',$dispatch['user_no'])
            ->where('id',$id)
            ->field('status')
            ->find();
        if (!$res){
            return $this->error('发生未知错误');
        }
        $row = Db::table('cq_project')->where('id',$id)->update(['status'=> -1,'updated_at'=>time()]);
        if ($row !=1){
            return $this->error('修改失败');
        }
        return $this->success('success',1,[]);
    }

    /**
     * 权限我的项目
     * @param $id
     * @param $dispatch
     * @param int $page
     * @param int $limit
     * @return array
     * @throws
     */
    public function allProject($id,$dispatch,$page = 0,$limit = 10)
    {
        if (!$dispatch['user_no']) {
            return $this->error('用户身份校验失败');
        }
        // 获取所有权限信息
        $rolo = Db::table('cq_position')
            ->field('id,p_id as pid')
            ->select()
            ->toArray();
        /**根据用户点击行为得出他想看的数据**/
        $self = Db::table('cq_position')
            ->where('belong',$id)
            ->column('id');
        // 递归出权限子集
        $want = [];
        foreach ($self as $value){
            $temp=get_all_child($rolo,$value);
            $want = array_merge($temp,$want);
            array_push($want,$value);
        }
        $want = array_unique($want);
        /**用户自己权限范围内**/
        $rolo_id = Db::table('cq_user')
            ->where('status', 1)
            ->where('user_no', $dispatch['user_no'])
            ->value('rolo_id');
        // 递归出当前登录者的子集权限和当前权限
        $ids = get_all_child($rolo,$rolo_id);
        array_push($ids,$rolo_id);
        $eq = array_intersect($want,$ids);
        if (empty($eq)){
            return $this->success('对应权限没有数据',1,[]);
        }
        /** 如果权限是最低权限 并且 这时候你只能看你自己的项目**/
        if (count($eq) == 1 && array_shift($eq)==$rolo_id){
            $uuid_arr = array();
            $uuid_arr[] = $dispatch['user_no'];
        }else{
            $key=array_search($rolo_id,$eq);
            if($key){
                unset($eq[$key]);
            }
            /**你只能看你的子集权限和你自己的项目**/
            $uuids = Db::table('cq_user')
                ->where('status', 1)
                ->where('rolo_id', 'in', $eq)
                ->column('user_no,rolo_id');
            $uuid_arr = array_keys($uuids);
            /**如果用户想看的正好是登录者部门**/
            $dpt=db('position')->where(['id'=>$rolo_id])->value('belong');
            if ($dpt == $id) {
                array_push($uuid_arr,$dispatch['user_no']);
            }
        }
        // 查出所有项目
        $project = Db::table('cq_project')
            ->alias('p')
            ->join('cq_user u','p.user_no = u.user_no','LEFT')
            ->join('cq_position a','u.rolo_id=a.id','LEFT')
            ->join('cq_department b','a.belong=b.id','LEFT')
            ->field('p.*,u.username,b.dpt_name')
            ->where('p.status', 1)
            ->where('p.user_no', 'in',$uuid_arr)
            ->order('p.updated_at','desc')
            ->page($page)
            ->limit($limit)
            ->paginate($limit)
            ->toArray();

        foreach ($project['data'] as &$v){
            $v['created_at']=date('Y-m-d H:i:s',$v['created_at']);
            $v['follow_status']=project_status($v['follow_status']);
        }
        return $this->success('success',1,$project);
    }

    /**
     * 权限我的成员列表
     * @param $id
     * @param $dispatch
     * @param $page
     * @param $limit
     * @return array
     * @throws \think\Exception
     */
    public function memberList($id,$dispatch,$page,$limit)
    {
        if (!$dispatch['user_no']) {
            return $this->error('用户身份校验失败');
        }
        // 获取所有权限信息
        $rolo = Db::table('cq_position')
            ->column('id,p_id','id');
        // 根据用户点击行为得出他想看的数据
        $see = Db::table('cq_position')
            ->where('belong',$id)
            ->column('id');
        // 递归出权限子集
        $son = [];
        foreach ($see as $value){
            $temp = $this->getTree($rolo,$value );
            $son = array_merge($temp,$son);
            array_push($son,$value);
        }
        $son = array_unique($son);

        // 当前用户的权限id
        $rolo_id = Db::table('cq_user')
            ->where('status', 1)
            ->where('user_no', $dispatch['user_no'])
            ->value('rolo_id');

        // 递归出当前登录者的子集权限和当前权限
        $ids = $this->getTree($rolo,$rolo_id );
        array_push($ids,$rolo_id);
        $eq = array_intersect($son,$ids);

        if (empty($eq)){
            return $this->success('对应权限没有数据',1,[]);
        }

        // 如果权限是最低权限 并且is_lead eq 0 这时候你只能看你自己的成员
        $userModel =  Db::table('cq_user')->where('status', 1);
        if (count($eq) == 1 && array_shift($eq)==$rolo_id){
            $userModel->where('user_no',$dispatch['user_no']);
            $count = Db::table('cq_user')->where('status', 1)->where('user_no',$dispatch['user_no'])->count();
        }else{
            //你只能看你的子集权限和你自己的成员
            array_pop($ids);
            $userModel->where('rolo_id', 'in', $ids)->whereOr('user_no',$dispatch['user_no']);
            $count = Db::table('cq_user')->where('status', 1)->where('rolo_id', 'in', $ids)->whereOr('user_no',$dispatch['user_no'])->count();
        }
        $list = $userModel->page(bcadd($page,1))
            ->limit($limit)
            ->field('user_no,phone,username,rolo_id,lastlogin_at')
            ->select()


            ->toArray();

        // 科室部门 左连接
        $dpt = Db::table('cq_department')
            ->alias('d')
            ->join('cq_position p','d.id = p.belong','LEFT')
            ->column('p.position_name,d.dpt_name','p.id');

        array_walk($list,array($this,'dealcallback'),$dpt);
        $result = compact('list','count');
        return $this->success('success',1,$result);
    }

    /**
     * array_walk 小回调
     * @param $value
     * @param $key
     * @param $dpt
     */
    public function dealcallback(&$value,$key,$dpt){
        $value['dpt_name'] = $dpt[$value['rolo_id']]['dpt_name'];
        $value['position_name'] = $dpt[$value['rolo_id']]['position_name'];
        $value['lastlogin_at'] =date( 'Y-m-d H:i:s',$value['lastlogin_at']);
    }

    /**
     * 小递归
     * @param $arr
     * @param int $pid
     * @return array
     */
    public function getTree($arr,$pid=0){
        $ids = array();
        foreach ($arr as $v){
            if ($v['p_id'] == $pid){
                $ids[] = $v['id'];
                $ids = array_merge($ids,$this->getTree($arr,$v['id']));
            }
        }
        return  $ids;
    }

    /**
     * 推送项目列表
     * @param $page
     * @param $limit
     * @param $keywords
     * @return array
     * @throws
     */
    public function crmPushProject($dispatch,$page,$limit,$data)
    {
        if (!$dispatch['user_no']){
            return $this->error('用户检测未登录');
        }
        
        $where=['a.status'=>1,'b.status'=>1,'a.user_no'=>$dispatch['user_no']];
        if($data['is_read']==0){
        	$where['a.is_read']=0;
        }
        if($data['is_read']==1){
        	$where['a.is_read']=1;
        }
        $push_obj = Db::table('cq_push_user_chain a')
            ->field('b.*')
            ->join('cq_push_project b','a.push_id=b.identification','left')
            ->where($where)
            ->order('b.updated_at','desc');
        
            
        if ($data['keywords']) {
        	$push_obj->where('b.company_name', 'like', '%' . $data['keywords'] . '%');
        }
        // 设置分页数据
        //Config::set('paginate.page',bcadd($page,1));
        $data = $push_obj->paginate($limit)->toArray();
       
        
        if(empty($data)){
            return $this->success('success',1,$data);
        }else{
             foreach ($data['data'] as &$value) {
                # code...
                //企业和园区相关
                if(isset($value['com_id'])&&$value['com_id']){
                	
                	/* //企业相关
                	if($value['type']==1){
                		$com_info=Db::connect(config('db_yd'))->table('yd_companys')
                		->field('label,invest_score,create_time as update_time')
                		->where(['identification'=>$value['com_id']])
                		->find();               		
                		$value['update_time']=$com_info['update_time'];
                	}
                   
                     //关注人数
                    $value['append_num']=db('user_collect_type_company')->where(['identification'=>$value['com_id']])->count(); */

                }else{
                   /*  $value['label']='';                   
                    $value['invest_score']='';
                    $value['update_time']=date('Y-m-d H:i:s');
                    $value['append_num']=0; */

                }

            }
        }
        array_walk($data['data'],array($this,'pushArrayWalk'));
        // json转化
        return $data;
    }

    /**
     * array_walk 小回调
     * @param $value
     * @param $key
     * @param $dpt
     */
    public function pushArrayWalk(&$value,$key){
        $value['industry'] = implode('@',array_column(unserialize($value['industry']),'name'));
        $value['chain'] = implode('@',array_column(unserialize($value['chain']),'name'));
        $value['city'] = implode('@',array_column(unserialize($value['city']),'name'));
    }

    /**
     * CRM 推送项目详情
     * @param $id
     * @param $dispatch
     * @return array
     * @throws
     */
    public function crmPushProjectDetail($id,$dispatch)
    {
        if (!$dispatch['user_no']) {
            return $this->error('用户检测未登录');
        }
        $res = Db::table('cq_push_project')->where('status', 1)->where('identification', $id)->find();
        if (empty($res)) {
            return $this->error('非法参数', '-1');
        }
        $res['industry'] =  implode('@',array_column(unserialize($res['industry']),'name'));
        $res['chain'] =  implode('@',array_column(unserialize($res['chain']),'name'));
        $res['city'] =  implode('@',array_column(unserialize($res['city']),'name'));

        /****已读****/
        Db::startTrans();
        try {
            // insert 一条数据
            Db::table('cq_push_user_chain')->where(['push_id'=>$id,'user_no'=>$dispatch['user_no']])->update(['is_read'=>1]);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            $msg  = "File：" . $e->getFile() . "\n";
            $msg .= "Line：" . $e->getLine() . "\n";
            $msg .= "Message：" . $e->getMessage() . "\n";
            var_dump($msg);
            // 回滚事务
            Db::rollback();
            $this->result['status'] = -1;
            $this->result['msg'] = 'add失败';
            return $this->result;
        }

        return $this->success('success', '1',$res);
    }

    /**
     * CRM add推送项目api
     * @param $data
     * @return array
     */
    public function crmPushProjectAdd($data)
    {
        $data['updated_at'] = $data['created_at'] = time();
        $data['status'] = 1;

        // 启动事务 update
        Db::startTrans();
        try {
            // insert 一条数据
            Db::table('cq_push_project')->insert($data);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            $msg  = "File：" . $e->getFile() . "\n";
            $msg .= "Line：" . $e->getLine() . "\n";
            $msg .= "Message：" . $e->getMessage() . "\n";
            var_dump($msg);
            // 回滚事务
            Db::rollback();
            $this->result['status'] = -1;
            $this->result['msg'] = 'add失败';
            return $this->result;
        }
        return $this->success('success',1);
    }

    /**
     * 首页项目库 add
     * @param $data
     * @param $dispatch
     * @return array
     */
    public function addProjectLib($data,$dispatch){
        if (!$dispatch['user_no']) {
            return $this->error('用户检测未登录');
        }
        $data['user_no'] = $dispatch['user_no'];
        $data['status'] = 1;
        $data['created_at'] = $data['updated_at'] = date('Y-m-d H:i:s',time());
        // 启动事务 update

        Db::startTrans();
        try {
            // insert 一条数据
            Db::table('cq_publish_project')->insert($data);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            $msg  = "File：" . $e->getFile() . "\n";
            $msg .= "Line：" . $e->getLine() . "\n";
            $msg .= "Message：" . $e->getMessage() . "\n";
            var_dump($msg);
            // 回滚事务
            Db::rollback();
            $this->result['status'] = -1;
            $this->result['msg'] = 'add失败';
            return $this->result;
        }
        return $this->success('success',1);
    }

    /**
     * 首页项目库 list
     * @param $data
     * @param $dispatch
     * @param $page
     * @param $limit
     * @return array
     * @throws \think\exception\DbException
     */
    public function projectLibList($data,$dispatch,$page,$limit){
        /* if (!$dispatch['user_no']) {
            return $this->error('用户检测未登录');
        } */
        $news_obj = Db::table('cq_publish_project')->field('id,contact,phone,company_name,product_name,type')
          //  ->where('user_no',$dispatch['user_no'])
            ->where('status',1);
        if ($data['keywords']){
            $news_obj->where('product_name','like','%'.$data['keywords'].'%');
        }
        if ($data['type']){
        	$news_obj->where(['type'=>$data['type']]);
        }
        // 设置分页数据
        Config::set('paginate.page',bcadd($page,1));
        $origin = $news_obj->order('grow desc,created_at desc')->paginate($limit)->toArray();
        
        return $this->success('success',1,$origin);
    }

    /**
     * 首页项目库 detail
     * @param $id
     * @param $dispatch
     * @return array
     * @throws
     */
    public function projectLibDetail($id,$dispatch)
    {
        if (!$dispatch['user_no']) {
            return $this->error('用户检测未登录');
        } 
        $res = Db::table('cq_publish_project')->field('id,contact,phone,company_name,product_name,type')
            ->where('status',1)
            //->where('user_no',$dispatch['user_no'])
            ->where('id',$id)
            ->find();
        if (empty($res)){
            return $this->success('success',1,[]);
        }
        return $this->success('success',1,$res);
    }

    /**
     * 首页项目 edit
     * @param $data
     * @param $dispatch
     * @return array
     * @throws
     */
    public function projectLibEdit($data,$dispatch)
    {
        if (!$dispatch['user_no']) {
            return $this->error('用户检测未登录');
        } 
        $res = Db::table('cq_publish_project')
            ->where('status',1)
            //->where('user_no',$dispatch['user_no'])
            ->where('id',$data['id'])
            ->find();
        if (empty($res)){
            return $this->error('网络错误');
        }
        // 启动事务 update
        Db::startTrans();
        try {
            // update 一条数据
            $upd['phone'] = $data['phone'];
            $upd['project_name'] = $data['project_name'];
            $upd['content'] = $data['content'];
            $upd['industry'] = $data['industry'];
            $upd['industry_id'] = $data['industry_id'];
            $upd['cooperation'] = $data['cooperation'];
            $upd['amount'] = $data['amount'];
            $upd['image'] = $data['image'];
            $upd['grow']=$data['grow'];
            
            $upd['contact']=$data['contact'];
            $upd['type']=$data['type'];
            $upd['product_name']=$data['product_name'];
            $upd['company_name']=$data['company_name'];
            
            $upd['updated_at'] = date('Y-m-d H:i:s',time());
            Db::table('cq_publish_project')->where('id',$data['id'])->update($upd);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            $msg  = "File：" . $e->getFile() . "\n";
            $msg .= "Line：" . $e->getLine() . "\n";
            $msg .= "Message：" . $e->getMessage() . "\n";
            var_dump($msg);
            // 回滚事务
            Db::rollback();
            $this->result['status'] = -1;
            $this->result['msg'] = 'update失败';
            return $this->result;
        }
        return $this->success('success',1);
    }

    /**
     * 首页项目 del
     * @param $id
     * @param $dispatch
     * @return array
     * @throws
     */
    public function projectLibDel($id,$dispatch)
    {
        /* if (!$dispatch['user_no']) {
            return $this->error('用户检测未登录');
        } */
        $res = Db::table('cq_project')
            ->where('status',1)
            //->where('user_no',$dispatch['user_no'])
            ->where('id',$id)
            ->find();
        if (empty($res)){
            return $this->error('网络错误');
        }
        // 启动事务 update
        Db::startTrans();
        try {
            $upd['status'] = 2;
            $upd['updated_at'] = time();
            Db::table('cq_project')->where('id',$id)->update($upd);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            $msg  = "File：" . $e->getFile() . "\n";
            $msg .= "Line：" . $e->getLine() . "\n";
            $msg .= "Message：" . $e->getMessage() . "\n";
            var_dump($msg);
            // 回滚事务
            Db::rollback();
            $this->result['status'] = -1;
            $this->result['msg'] = '删除失败';
            return $this->result;
        }
        return $this->success('success',1);
    }

    /**
     * 首页项目在首页展示 list
     * @param $reqData
     * @param $page
     * @param $limit
     * @return array
     * @throws \think\exception\DbException
     */
    public function indexProjectList($reqData,$page,$limit){
        $model = Db::table('cq_publish_project')->where('status',1)->order('updated_at','desc');
        if ($reqData['city_id']){
            $model->where('find_in_set(:id,city_id)',['id'=>$reqData['city_id']]);
        }
        if ($reqData['industry_id']){
            $model->where('find_in_set(:idd,industry_id)',['idd'=>$reqData['industry_id']]);
        }
        if ($reqData['cooperation']){
            $model->where('cooperation',$reqData['cooperation']);
        }
        if ($reqData['amount_scop_id']){
            $scop = Config::get('amount_scop')[$reqData['amount_scop_id']];
            $model->where('amount','between',array($scop['min'],$scop['max']));
        }
        if ($reqData['keywords']){
            $model->where('project_name','like','%'. $reqData['keywords'] .'%');
        }
        // 设置分页数据
        Config::set('paginate.page',$page);
        $result = $model->order('grow desc,created_at desc')->paginate($limit)->toArray();
        return $this->success('success',1,$result);
    }

    /**
     * 首页项目在首页展示 detail
     * @param $id
     * @return array
     * @throws
     */
    public function indexProjectDetail($id)
    {
        $res = Db::table('cq_publish_project')
            ->where('status',1)
            ->where('id',$id)
            ->find();
        if (empty($res)){
            return $this->error('网络错误');
        }
        return $this->success('success',1,$res);
    }

    /**
     * 新闻资讯 add
     * @param $data
     * @param $dispatch
     * @return array
     */
    public function newsAdd($data,$dispatch){
        if (!$dispatch['user_no']) {
            return $this->error('用户检测未登录');
        }
        $data['status'] = 1;
        $data['user_no'] = $dispatch['user_no'];
        $data['created_at'] = $data['updated_at'] = date('Y-m-d H:i:s',time());
        // 启动事务 update
        Db::startTrans();
        try {
            // insert 一条数据
            Db::table('cq_publish_news')->insert($data);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            $msg  = "File：" . $e->getFile() . "\n";
            $msg .= "Line：" . $e->getLine() . "\n";
            $msg .= "Message：" . $e->getMessage() . "\n";
            var_dump($msg);
            // 回滚事务
            Db::rollback();
            $this->result['status'] = -1;
            $this->result['msg'] = 'add失败';
            return $this->result;
        }
        return $this->success('success',1);
    }

    /**
     * 新闻资讯 list
     * @param $data
     * @param $dispatch
     * @param $page
     * @param $limit
     * @return array
     * @throws \think\exception\DbException
     */
    public function newsList($data,$dispatch,$page,$limit)
    {
        if (!$dispatch['user_no']) {
            return $this->error('用户检测未登录');
        }
        $news_obj = Db::table('cq_publish_news')
            //->where('user_no',$dispatch['user_no'])
            ->where('status',1);
        if ($data['keywords']){
            $news_obj->where('news_name','like','%'.$data['keywords'].'%');
        }
        // 设置分页数据
        Config::set('paginate.page',bcadd($page,1));
        $origin = $news_obj->order('grow desc,created_at desc')->paginate($limit)->toArray();
        return $this->success('success',1,$origin);
    }

    /**
     * 新闻资讯 eidt
     * @param $data
     * @param $dispatch
     * @return array
     * @throws
     */
    public function newsEdit($data,$dispatch){
        if (!$dispatch['user_no']) {
            return $this->error('用户检测未登录');
        }
        $res = Db::table('cq_publish_news')
            ->where('status',1)
            ->where('user_no',$dispatch['user_no'])
            ->where('identification',$data['identification'])
            ->find();
        if (empty($res)){
            return $this->error('网络错误');
        }
        // 启动事务 update
        Db::startTrans();
        try {
            // update 一条数据
            $upd['news_name'] = $data['news_name'];
            $upd['news_origin'] = $data['news_origin'];
            $upd['content'] = $data['content'];
            $upd['image'] = $data['image'];
            $upd['industry'] = $data['industry'];
            $upd['industry_id'] = $data['industry_id'];
            $upd['chain'] = $data['chain'];
            $upd['chain_id'] = $data['chain_id'];
            $upd['grow'] = $data['grow'];
            $upd['updated_at'] = date('Y-m-d H:i:s',time());
            Db::table('cq_publish_news')->where('identification',$data['identification'])->update($upd);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            $msg  = "File：" . $e->getFile() . "\n";
            $msg .= "Line：" . $e->getLine() . "\n";
            $msg .= "Message：" . $e->getMessage() . "\n";
            var_dump($msg);
            // 回滚事务
            Db::rollback();
            $this->result['status'] = -1;
            $this->result['msg'] = 'update失败';
            return $this->result;
        }
        return $this->success('success',1);
    }

    /**
     * 新闻资讯 del
     * @param $id
     * @param $dispatch
     * @return array
     * @throws
     */
    public function newsDel($id,$dispatch){
        if (!$dispatch['user_no']) {
            return $this->error('用户检测未登录');
        }
        $res = Db::table('cq_publish_news')
            ->where('status',1)
            ->where('user_no',$dispatch['user_no'])
            ->where('identification',$id)
            ->find();
        if (empty($res)){
            return $this->error('网络错误');
        }
        // 启动事务 update
        Db::startTrans();
        try {
            $upd['status'] = 2;
            $upd['updated_at'] = date('Y-m-d H:i:s',time());
            Db::table('cq_publish_news')->where('identification',$id)->update($upd);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            $msg  = "File：" . $e->getFile() . "\n";
            $msg .= "Line：" . $e->getLine() . "\n";
            $msg .= "Message：" . $e->getMessage() . "\n";
            var_dump($msg);
            // 回滚事务
            Db::rollback();
            $this->result['status'] = -1;
            $this->result['msg'] = '删除失败';
            return $this->result;
    }
        return $this->success('success',1);
    }

    /**
     * 新闻资讯 detail
     * @param $id
     * @param $dispatch
     * @return array
     * @throws
     */
    public function newsDetail($id,$dispatch){
        if (!$dispatch['user_no']) {
            return $this->error('用户检测未登录');
        }
        $res = Db::table('cq_publish_news')
            ->where('status',1)
            ->where('user_no',$dispatch['user_no'])
            ->where('identification',$id)
            ->find();
        if (empty($res)){
            return $this->success('success',1,[]);
        }
        return $this->success('success',1,$res);
    }

    /**
     * 新闻资讯 首页展示list
     * @param $page
     * @param $limit
     * @return array
     * @throws \think\exception\DbException
     */
    public function indexNewsList($page,$limit)
    {
        $news_obj = Db::table('cq_publish_news')
            ->where('status',1);
        // 设置分页数据
        Config::set('paginate.page',bcadd($page,1));
        $origin = $news_obj->order('grow desc,created_at desc')->paginate($limit)->toArray();
        foreach ($origin['data'] as &$val){
            $val['type_id']=0;
        }
        return $this->success('success',1,$origin);
    }

    /**
     * 新闻资讯 首页展示detail
     * @param $id
     * @return array
     * @throws
     */
    public function indexNewsDetail($id){
        $res = Db::table('cq_publish_news')
            ->where('status',1)
            ->where('identification',$id)
            ->find();
        if (empty($res)){
            return $this->error('网络错误');
        }
        return $this->success('success',1,$res);
    }

    /**
     * 深度分析
     * @param $data
     * @param $dispatch
     * @param $captcha
     * @return array
     */
    public function companyAnalyze($data,$dispatch)
    {
        if (!$dispatch['user_no']) {
            return $this->error('用户检测未登录');
        }
        // 启动事务 insert
        $data['user_no'] = $dispatch['user_no'];
        $data['created_at'] = $data['updated_at'] = date('Y-m-d H:i:s',time());
        
        
        Db::startTrans();
        try {
        	Db::table('cq_company_analyze')->insert($data);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            $msg  = "File：" . $e->getFile() . "\n";
            $msg .= "Line：" . $e->getLine() . "\n";
            $msg .= "Message：" . $e->getMessage() . "\n";
            //var_dump($msg);
            // 回滚事务
            Db::rollback();
            $this->result['status'] = -1;
            $this->result['msg'] = 'add失败';
            return $this->result;
        }
        return $this->success('success',1);

    }
}